<template>
  <div class="warehousearea">
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               :before-open="beforeOpen"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          @click="handleImport">
          导 入
        </el-button>
        <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permissionList" @click="handleExport">导 出</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permissionList" @click="handleDelete">删 除</el-button>
      </template>

      <!-- 现场图片表单自定义 -->
      <template slot="xczpForm">
        <div v-if="dialogType !== 'view'">
          <el-button
            size="small"
            type="primary"
            @click="uploadXCZP">
            上传图片
          </el-button>
          <span style="margin-left: 10px; color: #606266; font-size: 12px;">只能上传图片，最多选择3张</span>
          <input
            accept="image/*"
            ref="xczpUpload"
            id="xczpUpload"
            style="display: none;"
            type="file"
            @change="xczpUpload"
            multiple />
        </div>
      </template>

      <!-- 现场照片内容表单自定义 -->
      <template slot="xczpContentForm">
        <div class="xczp_content">
          <el-tag
            v-for="(item, index) in xczpFileList"
            :key="index"
            type="info"
            :closable="dialogType !== 'view'"
            @close="handleRemoveXCZP(index)"
          >
            <img
              :src="item.response.data.fileUrl"
              @click="previewXCZP(item)"
              alt />
          </el-tag>
        </div>
      </template>

      <!-- 现场照片表格自定义 -->
      <template slot="xczp" slot-scope="scope">
        <div class="ope_row_div">
          <span v-if="scope.row['xczp'] === '' || scope.row['bladeFiles'].length === 0">-</span>
          <el-button v-else type="text" @click="handleViewPhoto(scope.row)">查看</el-button>
        </div>
      </template>

      <!--绑定摄像头-->
     <template slot="zdjg" slot-scope="scope">
       <el-form label-width="0px">
         <el-badge :value="(dataCAm[scope.row.id]==null?0:dataCAm[scope.row.id])" class="item">
           <el-button type="warning" size="small" @click="handleCamera(scope.row.id)">绑定 摄像头</el-button>
         </el-badge>
       </el-form>
     </template>

     <!--巡检点-->
      <template slot="ckxjjl">
        <el-form label-width="0px">
          <td style="border: 0px">
            <el-button type="primary" size="mini">查看巡查点</el-button>
          </td>
        </el-form>
      </template>

      <template slot="idsLabel">
        <span style="color:#F56C6C">*</span><span>绑定风险点:</span>
      </template>
      <template slot="idsForm">
        <el-form label-width="0px">
          <el-button type="success" size="small" @click="handleRisk">选择 风险点</el-button>
          <span v-if="riskTagsErr" class="error">请选择风险点</span>
          <div class="risk_point_list">
            <el-tag :key="index" v-for="(tag, index) in riskTags" closable :disable-transitions="false" @close="closeRiskTag(index)">{{tag.fxdbh}}</el-tag>
          </div>
        </el-form>
      </template>
      <!-- 地图表单自定义 -->
      <template slot="mapForm">
        <div v-if="showMap">
          <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
            <el-input placeholder="关键词查询" v-model="searchWord" style="position:absolute;top:10px;left:10px;width:180px;">
              <template slot="append">
                <el-button icon="el-icon-search" id="citySearch"></el-button>
              </template>
            </el-input>
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-marker :position="mapPosition" :dragging="true"></bm-marker>
          </baidu-map>
        </div>
      </template>
    </avue-crud>
    <!-- 绑定风险点弹窗 -->
    <el-dialog title="选择 风险点" :visible.sync="dialogRisk" append-to-body @close='closeDialog' width="1200px" class="warehousearea">
      <avue-crud :option="riskOption"
                 :table-loading="riskLoading"
                 :data="riskData"
                 :page.sync="riskPage"
                 ref="riskCrud"
                 @search-change="riskSearchChange"
                 @search-reset="riskSearchReset"
                 @selection-change="riskSelectionChange"
                 @current-change="riskCurrentChange"
                 @size-change="riskSizeChange">
      </avue-crud>
      <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="chooseRisk()">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 绑定摄像头弹窗 -->
    <el-dialog title="选择 摄像头" :visible.sync="dialogCamera" append-to-body @close='closeDialogCamera' width="1200px" class="warehousearea">
      <avue-crud :option="cameraOption"
                 :table-loading="cameraLoading"
                 :data="cameraData"
                 :page.sync="cameraPage"
                 ref="cameraCrud"
                 @search-change="cameraSearchChange"
                 @search-reset="cameraSearchReset"
                 @selection-change="cameraSelectionChange"
                 @current-change="cameraCurrentChange"
                 @size-change="cameraSizeChange">
      </avue-crud>
      <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialogCamera">取 消</el-button>
          <el-button type="primary" @click="chooseCamera()">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 弹窗：图片 -->
    <viewpicture
      :localPicBox="localPicBox"
      :localPictures="localPictures"
      @confirmViewPicture="confirmViewPicture"
      @handleClosePicBox="handleClosePicBox">
    </viewpicture>
    <!-- 导入弹窗 -->
    <el-dialog title="数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
  </div>
</template>

<script>
import {getList, remove, update, add,getDetail,getrisk,bindingCamera} from "@/api/mmhi/warehousearea";
import {mapGetters} from "vuex";
import viewpicture from "@/views/saferisk/components/viewpicture";
import {getCameraBindingList,getCameraBinding} from "@/api/mmhi/major_supe_hazard_chem";
import {getToken} from "@/util/auth";
import {num, removePic,uploadFiles} from "@/api/mmhi/prod_plant";
import {validateDigit} from "@/api/mmhi/validate";

export default {
  components:{
    viewpicture,
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      dataCAm:{},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      localPicUrl: "",
      localPicBox: false,
      //照片上传设置
      xczpFileList: [],
      dialogType:'',
      localPictures: [],
      photoBox: false,
      attachBox: false,
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        dialogWidth: 950,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        //excelBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "库区编号",
            prop: "kqbh",
            span: 30,
            maxlength:15,
            align: "center",
            search: true,
            rules: [{
              required: true,
              validator: validateDigit,
              trigger: "blur"
            }]
          },
          {
            label: "库区名称",
            prop: "kqmc",
            align: "center",
            maxlength:25,
            rules: [{
              required: true,
              message: "请输入库区名称",
              trigger: "blur"
            }]
          },
          {
            label: "在厂区的位置",
            prop: "zcqdwz",
            align: "center",
            maxlength:50,
            width: "100px",
            rules: [{
              required: true,
              message: "请输入在厂区的位置",
              trigger: "blur"
            }]
          },
          {
            label: "所处环境功能区",
            prop: "schjgnq",
            width: "120px",
            maxlength:25,
            align: "center",
            rules: [{
              required: true,
              message: "请输入所处环境功能区",
              trigger: "blur"
            }]
          },
          {
            label: "库区面积",
            prop: "kqmj",
            maxlength:2,
            align: "center",
            rules: [{
              required: true,
              validator: validateDigit,
              trigger: "blur"
            }]
          },
          {
            label: "库房个数",
            prop: "kfgs",
            align: "center",
            maxlength:2,
            rules: [{
              required: true,
              validator: validateDigit,
              trigger: "blur"
            }]
          },
          {
            label: "相邻库房最小间距",
            prop: "xlkfzxjj",
            width: "120px",
            align: "center",
            maxlength:5,
            rules: [{
              required: true,
              validator: validateDigit,
              trigger: "blur"
            }]
          },
          {
            label: "所属危险化学品重大危险源编码",
            prop: "sswxhxpzdwxybm",
            width: "200px",
            align: "center",
            maxlength:15,
            rules: [{
              required: true,
              message: "所属危险化学品重大危险源编码",
              trigger: "blur"
            }]
          },
          {
            label: "现场图片",
            prop: "xczp",
            align: "center",
            slot: true,
            span: 24,
            width: 80,
            formslot:true,
          },
          {
            label: "",
            prop: "xczpContent",
            hide: true,
            span: 24,
            formslot: true
          },
          {
            label: '',
            prop: 'map',
            span: 24,
            hide: true,
            formslot: true,
          },
          {
            label: "经度",
            prop: "jd",
            width:90,
            align: "center",
            span: 6,
            rules: [{
              required: true,
              message: "请输入经度",
              trigger: "blur"
            }]
          },
          {
            label: "纬度",
            prop: "wd",
            width:90,
            span: 6,
            align: "center",
            rules: [{
              required: true,
              message: "请输入纬度",
              trigger: "blur"
            }]
          },
          {
            label: "重点监管",
            width: "120px",
            prop: "zdjg",
            slot: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: false,
            align: "center"
          },
          {
            label: "操作",
            prop: "ckxjjl",
            width: "120px",
            slot: true,
            addDisplay: false,
            editDisplay: false,
            hide: false,
            align: "center",
            viewDisplay: false,
          },
          {
            label: "风险点",
            prop: "fxdbh",
            align: "center",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "绑定风险点",
            prop: "ids",
            align: "center",
            hide: true,
            viewDisplay: false,
            formslot:true,
            labelslot:true
          },
          {
            label: "备注",
            prop: "bz",
            align: "center",
            hide: true,
            viewDisplay: true,
            row: true,
            rules: [{
              required: false,
              message: "备注",
              trigger: "blur"
            }]
          },
          {
            label: "企业id",
            prop: "bladeDeptId",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "租户id",
            prop: "tenantId",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "创建人",
            prop: "createUser",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          },
          {
            label: "创建部门",
            prop: "createDept",
            hide: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false
          }
        ]
      },
      data: [],
      mapPosition: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      center: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      zoom: 10,
      dragging: false,
      showMap: true,
      searchWord: "",

      dialogCamera: false,
      cameraQuery: {},
      cameraLoading: true,
      cameraPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      cameraSelectionList: [],
      cameraOption: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        menu: false,
        addBtn: false,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: "摄像头名称",
            prop: "sxtmc",
            align: "center",
            search: true
          },
          {
            label: "摄像头ID",
            prop: "sxtid",
            align: "center"
          },
          {
            label: "安装位置",
            prop: "azwz",
            align: "center"
          },
          {
            label: "所属区域",
            prop: "ssqy",
            align: "center"
          }
        ]
      },

      cameraData: [],
      selectCamera: {},
      dataCameraBindingList: [],
      productionSiteBindingId: [],

      dialogRisk: false,
      riskQuery: {},
      riskLoading: true,
      riskPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      riskSelectionList: [],
      riskOption: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        menu: false,
        addBtn: false,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: "风险点名称",
            prop: "fxdmc",
            align: "center",
            search: true
          },
          {
            label: "风险类别",
            prop: "fxfl",
            align: "center"
          },
          {
            label: "事故类型",
            prop: "zysglx",
            align: "center"
          },
          {
            label: "所属部门",
            prop: "ssbm",
            align: "center"
          }
        ]
      },
      riskData: [],
      riskTags: [],
      riskTagsErr: false,
      selectRisk: {},


      cameraTags: [],
      cameraTagsErr: false,
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [{
          label: '模板上传',
          prop: 'excelFile',
          type: 'upload',
          drag: true,
          loadText: '模板上传中，请稍等',
          showFileList: false,
          span: 24,
          propsHttp: {
            fileName: 'multipartFile',
            res: 'data'
          },
          tip: '请上传 .xls,.xlsx 标准格式文件',
          action: "/api/warehouseArea/import ",
          headers: {}
        },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      },
    };
  },
  watch: {
    'form.tenantId'() {
      if (this.form.tenantId !== '' && this.initFlag) {
        this.initData(this.form.tenantId);
      }
    },
    // 'excelForm.isCovered'() {
    //   if (this.excelForm.isCovered !== '') {
    //     const column = this.findObject(this.excelOption.column, "excelFile");
    //     column.action = `/api/warehouseArea/import=${this.excelForm.isCovered}`;
    //   }
    // },
    // 表单经度
    'form.jd' (val) {
      if(val) {
        this.mapPosition.lng = val / 1
      }
    },

    // 表单纬度
    'form.wd' (val) {
      if(val) {
        this.mapPosition.lat = val / 1
      }
    }
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.warehousearea_add, true),
        viewBtn: this.vaildData(this.permission.warehousearea_view, true),
        delBtn: this.vaildData(this.permission.warehousearea_delete, true),
        editBtn: this.vaildData(this.permission.warehousearea_edit, true)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    player () {
      return this. $refs. videoPlayer. player
    },
    //现场照片id
    picIds() {
      let picIds = [];
      this.selectionList.forEach(ele => {
        picIds.push(ele.xczp);
      });
      return picIds.join(",");
    }

  },
  created() {
    this.getNum();
  },

  methods: {
    // 弹出导入框
    handleImport() {
      this.excelBox = true;
    },

    // 导入前判断
    beforeUpload(file, done, loading) {
      this.isFailed = false;
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls'
      const extension2 = testmsg === 'xlsx'
      if(!extension && !extension2) {
        this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
        loading()
      } else {
        done()
      }
    },

    // 导入失败后
    uploadError(error, column) {
      console.log(error,column);
      this.isFailed = true;
    },

    // 导入成功后
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },

    // 取消
    cancle() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },


    xczpUpload(element) {
      console.log(element);
      if(this.$refs.xczpUpload.files.length + this.xczpFileList.length > 3) {
        this.$message.warning("最多上传3张现场图片!");
        this.$refs.xczpUpload.value = null;
        return;
      }
      let formData = {};
      let files = this.$refs.xczpUpload.files;
      formData = new FormData();
      for(let i = 0 ; i < files.length ; i++) {
        formData.append("files", files[i]);
      }
      uploadFiles(formData).then(res => {
        if(!res.data.success) {
          return;
        }
        var resData = res.data.data;
        resData.forEach(item => {
          this.xczpFileList.push({
            name: item.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: item
            }
          });
        });
        this.$refs.xczpUpload.value = null;
      });
    },
    // 点击上传图片按钮
    uploadXCZP() {
      document.getElementById("xczpUpload").click();
    },
    // 获取现场照片ids
    formatPictureIds(filelist) {
      var ids = [];
      filelist.forEach(item => {
        ids.push(item.response.data.id);
      });
      return ids.join(",");
    },
    // 删除现场照片
    handleRemoveXCZP(index) {
      this.xczpFileList.splice(index, 1);
    },
    // 上传现场图片前
    beforeUploadXCZP(file) {
      var isLt2M = file.size / 1024 / 1024 < 2;
      var isLimit = (this.xczpFileList.length + 1) <= 3 ;
      if (!isLt2M) {
        this.$message.warning('图片大小不能超过2MB!');
      }
      if (!isLimit) {
        this.$message.warning('最多上传3张现场图片!');
      }
      return isLt2M && isLimit;
    },

    // 上传现场图片成功
    uploadXCZPSuccess(response, file, fileList) {
      if(response.code !== 200 || response.success !== true) {
        return;
      }
      this.xczpFileList = [];
      fileList.forEach(item => {
        this.xczpFileList.push({
          name: item.name,
          response: {
            code: 200,
            data: Array.isArray(item.response.data) === true ? item.response.data[0] : item.response.data,
            msg: "操作成功",
            success: true
          }
        });
      });
    },
    // 查看现场照片
    handleViewPhoto(row) {
      this.localPictures = row.bladeFiles;
      this.localPicBox = true;
    },
    // 点击图片列表中已上传的现场图片
    previewXCZP(file) {
      if(file.response && file.response.code === 200 && file.response.data && file.response.data.fileUrl) {
        this.localPictures = [file.response.data];
        this.localPicBox = true;
      }
    },

    // 确认照片
    confirmViewPicture() {
      this.localPicBox = false;
    },

    // 关闭弹窗
    handleClosePicBox() {
      this.localPicBox = false;
    },
    /**
     * 弹窗：图片
     */

    // 导入前判断
    photobeforeUpload(file, done, loading) {
      this.isFailed = false;
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'jpg'
      const extension2 = testmsg === 'png'
      if(!extension && !extension2) {
        this.$message.warning('请上传 .jpg,.png 标准格式文件!');
        loading()
      } else {
        done()
      }
    },
    // 导入失败后
    photouploadError(error, column) {
      console.log(error,column);
      this.isFailed = true;
    },
    // 导入成功后
    photouploadAfter(res, done) {
      done();
      if(this.isFailed === true) {
        return;
      }
      this.photoBox = false;
      this.$message.success("上传成功");
      this.cancle();
    },
    //照片打开
    photoImg() {
      this.photoBox = true;
    },



    // 打开选择风险点弹窗
    handleRisk() {
      this.dialogRisk = true;
      this.riskOnLoad(this.riskPage);
    },

    // 关闭选择风险点弹窗
    closeDialog() {
      this.riskPage.currentPage = 1;
      this.dialogRisk = false;
      this.riskSelectionClear();
    },

    // 风险点获取表格数据
    riskOnLoad(page, params = {}) {
      this.riskLoading = true;
      getrisk(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.riskPage.total = data.total;
        this.riskData = data.records;
        this.riskLoading = false;
        if(this.selectRisk !== undefined && JSON.stringify(this.selectRisk) !== "{}" && this.riskTags.length !== 0) {
          this.$nextTick(() => {
            this.riskData.forEach(row => {
              if(this.selectRisk[row.id] !== undefined) {
                this.$refs.riskCrud.toggleRowSelection(row, true);
              }
            })
          })
        }
      });
    },

    // 风险点清空勾选
    riskSelectionClear() {
      this.riskSelectionList = [];
      this.$refs.riskCrud.toggleSelection();
    },

    // 风险点搜索条件改变事件
    riskSearchChange(params, done) {
      this.riskQuery = params;
      this.riskPage.currentPage = 1;
      this.riskOnLoad(this.riskPage, params);
      done();
    },

    // 风险点清空搜索条件
    riskSearchReset() {
      this.riskQuery = {};
      this.riskOnLoad(this.riskPage);
    },

    // 风险点勾选
    riskSelectionChange(list) {
      this.riskSelectionList = list;
    },

    // 风险点换页数
    riskCurrentChange(currentPage){
      var pageSelectIds = [];
      var pageAllIds = [];
      this.riskSelectionList.forEach(item => {
        this.selectRisk[item.id] = item;
        pageSelectIds.push(item.id);
      });
      this.riskData.forEach(item => {
        pageAllIds.push(item.id);
      });
      for(var id in this.selectRisk) {
        if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
          delete this.selectRisk[id];
        }
      }
      this.riskPage.currentPage = currentPage;
      this.riskOnLoad(this.riskPage);
    },

    // 风险点换每页显示数量
    riskSizeChange(pageSize){
      this.riskPage.pageSize = pageSize;
      this.riskOnLoad(this.riskPage);
    },

    // 选择风险点
    chooseRisk() {
      var pageSelectIds = [];
      var pageAllIds = [];
      this.riskSelectionList.forEach(item => {
        this.selectRisk[item.id] = item;
        pageSelectIds.push(item.id);
      });
      console.log(this.riskSelectionList+101010)
      console.log(this.selectRisk+101010)
      this.riskData.forEach(item => {
        pageAllIds.push(item.id);
      });
      for(let id in this.selectRisk) {
        if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
          delete this.selectRisk[id];
        }
      }
      if(this.selectRisk === undefined || JSON.stringify(this.selectRisk) === "{}") {
        this.$message.warning("请选择风险点");
        return;
      }
      this.riskTagsErr = false;
      this.riskTags = [];
      for(let id in this.selectRisk) {
        this.riskTags.push(this.selectRisk[id]);
      }
      this.closeDialog();
    },

    // 删除某一个risk标签
    closeRiskTag(index) {
      this.riskTags.splice(index, 1);
      if(this.riskTags.length === 0) {
        this.riskTagsErr = true;
      }
    },


    // 打开绑定摄像头弹窗
    handleCamera(id) {
      this.productionSiteBindingId = id;
      this.dialogCamera = true;
      //调用获取对应绑定摄像头集合
      getCameraBindingList(id, 2).then((data) => {
        this.dataCameraBindingList=data.data.data
      });
      this.cameraOnLoad(this.cameraPage);
    },

    // 关闭绑定摄像头弹窗
    closeDialogCamera() {
      this.cameraPage.currentPage = 1;
      this.dialogCamera = false;
      this.cameraSelectionClear();
    },

    // 摄像头获取表格数据
    cameraOnLoad(page, params = {}) {
      this.cameraLoading = true;
      getCameraBinding(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.cameraPage.total = data.total;
        this.cameraData = data.records;
        this.cameraLoading = false;
        console.log(this.selectCamera);
        this.$nextTick(() => {
          this.cameraData.forEach(row => {
            this.dataCameraBindingList.forEach(item => {
              if(item.cameraId===row.id){
                this.$refs.cameraCrud.toggleRowSelection(row, true);
              }
            })
          })
        })
      });
    },

    // 绑定摄像头清空勾选
    cameraSelectionClear() {
      this.cameraSelectionList = [];
      this.$refs.cameraCrud.toggleSelection();
    },


    // 摄像头搜索条件改变事件
    cameraSearchChange(params, done) {
      this.cameraQuery = params;
      this.cameraPage.currentPage = 1;
      this.cameraOnLoad(this.cameraPage, params);
      done();
    },

    // 摄像头清空搜索条件
    cameraSearchReset() {
      this.cameraQuery = {};
      this.cameraOnLoad(this.cameraPage);
    },

    // 摄像头勾选
    cameraSelectionChange(list) {
      this.cameraSelectionList = list;
    },

    // 摄像头换页数
    cameraCurrentChange(currentPage){
      var pageSelectIds = [];
      var pageAllIds = [];
      this.cameraSelectionList.forEach(item => {
        this.selectCamera[item.id] = item;
        pageSelectIds.push(item.id);
      });
      this.cameraData.forEach(item => {
        pageAllIds.push(item.id);
      });
      for(var id in this.selectCamera) {
        if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
          delete this.selectCamera[id];
        }
      }
      this.cameraPage.currentPage = currentPage;
      this.cameraOnLoad(this.cameraPage);
    },

    // 摄像头换每页显示数量
    cameraSizeChange(pageSize){
      this.cameraPage.pageSize = pageSize;
      this.cameraOnLoad(this.cameraPage);
    },

    // 选择摄像头
    chooseCamera(done,loading) {
      var pageSelectIds = [];
      var pageAllIds = [];
      this.cameraSelectionList.forEach(item => {
        this.selectCamera[item.id] = item;
        pageSelectIds.push(item.id);
      });
      this.cameraData.forEach(item => {
        pageAllIds.push(item.id);
      });
      for(let id in this.selectCamera) {
        if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
          delete this.selectCamera[id];
        }
      }

      var ids = pageSelectIds.join(",");
      var id = this.productionSiteBindingId;
      bindingCamera(ids,id).then(() => {
        this.$message.success("绑定成功!");
        this.closeDialogCamera();
        this.onLoad(this.page);
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    //新增
    rowSave(row, done, loading) {
      row.xczp = this.xczpFileList.length === 0 ? "" : this.formatPictureIds(this.xczpFileList);
      if(this.riskTags.length === 0) {
        this.riskTagsErr = true;
        loading();
        return;
      }
      delete row.fxdbh;
      var idsArr = [];
      this.riskTags.forEach(item => {
        idsArr.push(item.id);
      });
      row.ids = idsArr.join(",");

      add(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    //获取绑定数
    getNum() {
      num().then((data) => {
        this.dataCAm=data.data.data
      }, error => {
        window.console.log(error);
      });
    },





    // 编辑
    rowUpdate(row, index, done,loading) {
      row.xczp=this.xczpFileList.length==0?"":this.formatPictureIds(this.xczpFileList)
      if(this.riskTags.length === 0) {
        this.riskTagsErr = true;
        loading();
        return;
      }
      var idsArr = [];
      var updateData = {
        id: row.id,
        fxdbh: row.fxdbh,
        fxdmc: row.fxdmc,
        kqbh: row.kqbh,
        kqmc: row.kqmc,
        zcqdwz: row.zcqdwz,
        schjgnq: row.schjgnq,
        kqmj: row.kqmj,
        kfgs: row.kfgs,
        xlkfzxjj: row.xlkfzxjj,
        sswxhxpzdwxybm: row.sswxhxpzdwxybm,
        xczp: row.xczp,
        jd: row.jd,
        wd: row.wd,
        zdjg: row.zdjg,
        ckxjjl: row.ckxjjl,
        bz: row.bz,
        bladeDeptId: row.bladeDeptId,
        tenantId: row.tenantId,
        createUser: row.createUser,
        createDept: row.createDept,
        ids: ""
      };
      this.riskTags.forEach(item => {
        idsArr.push(item.id);
      });
      updateData.ids = idsArr.join(",");
      update(updateData).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      },error => {
        window.console.log(error);
        loading();
      });
    },
    handleDownload(row) {
      window.open(`${row.link}`);
    },
    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.xczp!="") {
          removePic(row.xczp);
        }
        return remove(row.id);
      }).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
      });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.picIds.split(",").forEach(picId=>{
          if (picId!=="") {
            removePic(picId);
          }
        });
        return remove(this.ids);
      }).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        this.$refs.crud.toggleSelection();
      });
      this.pic=false
    },

    beforeOpen(done, type) {

      switch(type) {
        case 'add':
          this.dialogType =''
          this.xczpFileList = [];
          this.showMap = true;
          this.mapPosition = {
            lng: 121.4472540000,
            lat: 31.3236200000
          };
          this.center = {
            lng: 121.4472540000,
            lat: 31.3236200000
          };
          done();
          break
        case 'edit':
          this.dialogType =''
          this.showMap = true;
          this.center = {
            lng: this.form.jd,
            lat: this.form.wd
          };
          this.zoom = 8;
          this.xczpFileList = [];
          this.form.bladeFiles.forEach(item => {
            this.xczpFileList.push({
              name: item.fileName,
              response: {
                code: 200,
                data: item,
                msg: "操作成功",
                success: true
              }
            });
          });
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
          done();
          break
        case 'view':
          this.xczpFileList = [];
          this.form.bladeFiles.forEach(item => {
            this.xczpFileList.push({
              name: item.fileName,
              response: {
                code: 200,
                data: item,
                msg: "操作成功",
                success: true
              }
            });
          });
          this.showMap = false;
          this.dialogType = type;
          done();
          break
        default:
          break
      }
      this.riskTagsErr = false;
      this.riskTags = [];
      this.selectRisk = {};
      if (type === "edit") {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.form.riskManagements.forEach(item => {
            this.riskTags.push(item);
            this.selectRisk[item.id] = item;
            console.log(this.selectRisk+1111111)
          });
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        this.getNum();
      });
    },
    // 地图处理事件
    handler({BMap, map}) {
      let _this = this;
      map.addEventListener('click', function(e) {
        _this.form.jd = e.point.lng
        _this.form.wd = e.point.lat
      });

      _this.$nextTick(() => {
        document.getElementById('citySearch').addEventListener('click', function() {
          let localSearch = new BMap.LocalSearch(map)
          localSearch.setSearchCompleteCallback(searchResult => {
            let poi = searchResult.getPoi(0)
            if(!poi) {
              return _this.$message.warning('该地址不存在')
            } else {
              _this.center = {
                lng: poi.point.lng,
                lat: poi.point.lat
              }
              _this.form.jd = poi.point.lng
              _this.form.wd = poi.point.lat
            }
          });
          localSearch.search(_this.searchWord);
        });
      })
    },
    handleTemplate() {
      window.open(`/api/warehouseArea/export-template?${this.website.tokenHeader}=${getToken()}`);
    },
    handleExport() {
      this.$confirm("是否导出仓库区信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.open(`/api/warehouseArea/export-WarehouseArea?${this.website.tokenHeader}=${getToken()}`);
      });
    },
  }
};
</script>

<style>
.point_list {
  margin-top: 5px;
}
</style>
<style lang="scss" scpoed>
.map {
  width: 100%;
  height: 500px;
}
.item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>
<style lang="scss">
  .error{
    color: red;
    font-size: 12px;
    margin-left: 5px;
  }
.warehousearea {
  .el-form-item__label {
    width: 100px !important;
  }
  .avue-form__row {
    .el-form-item__content {
      margin-left: 100px !important;
    }
  }
}
</style>
<style lang="scss" scpoed >
@import "./styles/riskpointscoped.scss";
</style>
<style lang="scss">
@import "./styles/riskpointglobal.scss";
</style>
